package com.cppe.http;

import android.util.Log;

import com.cppe.entity.User;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class RxHttp {

    public static void post(String url, Map<String, Object> params, HttpCallBack callBack) {

        Observable.create((ObservableOnSubscribe<String>) emitter -> OkClient.getInstance().doPost(url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                emitter.onError(e);
                emitter.onComplete();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    emitter.onNext(response.body().string());
                } else {
                    emitter.onError(new Exception(response.body().string()));
                }
                emitter.onComplete();
            }
        })).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        callBack.start(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        callBack.success(s);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //需要判定类型
                        callBack.error(e.toString());
                        callBack.complete();
                    }

                    @Override
                    public void onComplete() {
                        callBack.complete();
                    }
                });
    }

}
